package com.ruoyi.group.service.impl;

import java.sql.Wrapper;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.group.mapper.ContractMapper;
import com.ruoyi.group.domain.Contract;
import com.ruoyi.group.service.IContractService;

/**
 * 合同信息Service业务层处理
 *
 * @author Zzz
 * @date 2022-11-27
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {

    @Autowired
    private ISysUserService userService;
    /**
     * 查询合同信息列表
     *
     * @param contract 合同信息
     * @return 合同信息
     */
    @Override
    public List<Contract> selectContractList(Contract contract) {
        List<Contract> contracts = getBaseMapper().selectContractList(contract);
        for (Contract con:contracts) {
            SysUser sysUser = userService.selectUserById(con.getInputUser());
            con.setUserName(sysUser.getNickName());
        }
        return contracts;
    }

    @Override
    public boolean save(Contract entity) {
        entity.setAffixSealState(0);
        entity.setAuditState(0);
        entity.setNullifyState(0);
        Long userId = SecurityUtils.getUserId();
        entity.setInputUser(userId);
        entity.setInputTime(new Date());
        super.save(entity);
        return true;
    }

    @Override
    public int updateSeal(Long id) {
        LambdaUpdateWrapper<Contract> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Contract::getAffixSealState,1).eq(Contract::getId,id);
        super.update(wrapper);
        return 1;
    }

    @Override
    public void updateAudit(Long id, Boolean result) {
        if (result){
            LambdaUpdateWrapper<Contract> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Contract::getAuditState,1).eq(Contract::getId,id);
            super.update(wrapper);
            return;
        }
        LambdaUpdateWrapper<Contract> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Contract::getAuditState,-1).eq(Contract::getId,id);
        super.update(wrapper);
    }

    @Override
    public int updateNullifyState(Long id) {
        LambdaUpdateWrapper<Contract> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Contract::getNullifyState,-1).eq(Contract::getId,id);
        super.update(wrapper);
        return 1;
    }
}
